package com.gitee.jmliu1983.javautils;

import java.io.IOException;
import java.io.RandomAccessFile;

public class TextStreamUtils {
	/** 从本地文本文件中指定偏移位置开始，读取一行字符串。
	 * @param filePath 文件的路径
	 * @param offset 指定的偏移位置
	 * @param sb StringBuilder实例，用来存储读取到的字符串
	 * @return 读取字符串后的指针偏移量，用于顺序进行下一次读取
	 */
	public static Long readLineFromFileWithOffset(String filePath, Long offset, StringBuilder sb) {
		sb.setLength(0); // 初始化StringBuilder
		Long accumuatedOffset = offset;
		String stringReadUntilLineEnd = "";
		try (RandomAccessFile file = new RandomAccessFile(filePath, "r")) {
			file.seek(offset);
			boolean skipFlag = true;
			while (skipFlag) {
				stringReadUntilLineEnd = file.readLine();
				if (stringReadUntilLineEnd == null) {
					return -1L;
				} else {
					skipFlag = stringReadUntilLineEnd.trim().compareTo("") == 0;
					byte[] bytes = stringReadUntilLineEnd.getBytes();
					accumuatedOffset += bytes.length;
				}
			}
			sb.append(stringReadUntilLineEnd);
			return accumuatedOffset + 1;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
